# Create your views here.
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.template import RequestContext

from django.conf import settings
from django.contrib  import admin

def general(request, model_admin):
	ordered_inlines = []
	for m, a in  admin.site._registry.items():
		if a.__class__.__name__.lower() == model_admin:
			if hasattr(a, 'ordered_inlines'):
				ordered =  a.ordered_inlines
				for o in ordered:
					if isinstance(o, tuple):
						c = o[1](m, admin.site)
						related = c.get_formset(None,None).fk.rel.related_name
						ordered_inlines.append((o[0], related))
				break
	return render_to_response ('inlines.js',locals(), context_instance=RequestContext(request))
		
def calculated(request, model):
	gets = []
	for model_class, a in  admin.site._registry.items():
		if model_class.__name__.lower() == model:
			m = model_class()
			if hasattr(m, "gets"):
				for f in m.gets:
					import inspect
					code = inspect.getsourcelines(getattr(m,"get_"+f))[0][1:]
					depends = []
					for line in code:
						import re
						fields = re.findall("self.(\w+)",line)
						if fields:
							depends += fields
					gets.append((f, code, depends))
			inlines = [inline(model_class, admin.site).get_formset(None,None).fk.rel.related_name for inline in  a.inlines]
	return render_to_response ('calculated.js',locals(), context_instance=RequestContext(request))
		
def to_str(d):
	if d:
		return str(d)
	else:
		return None

from django import forms
import simplejson as json

#class GenericForm(forms.ModelForm):
#	class Meta:
#		model = Movimiento

def get_value(request, model, field):
	exec("M = " + model)
	#MForm = forms.form_for_model(M)
	if request.method == "POST":
		form = GenericForm(request.POST)
	else:
		form = GenericForm(request.GET)
		
	m = form.save(commit=False)
	
	v = eval("m.get_" + field + "()")
	v = json.dumps(to_str(v))
	return HttpResponse(v, mimetype='application/javascript')

